<template>
  <div class="app-container">
    <el-card style="width:100%">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="queryInfo.key"
            placeholder="请输入内容"
            clearable
            @clear="getTheseInfo"
          >
            <!-- 搜索框按钮 -->
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getTheseInfo"
            />
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button
            class="addUser"
            @click="addVisible = true"
          >添加用户</el-button>
        </el-col>
      </el-row>

      <el-table
        :data="list"
        border
        fit
        highlight-current-row
        current-row-key
        stripe
        style="width:100%"
        :row-style="{ height: '60px' }"
      >
        <el-table-column align="center" label="序号" width="58" prop="aid" />

        <el-table-column align="center" label="姓名">
          <template slot-scope="scope">
            <el-tag effect="plain" type="warning">{{ scope.row.realname }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          label="账号"
          prop="account"
        />

        <el-table-column width="70px" align="center" label="性别">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.sex === '男'" type="success" size="mini">男</el-tag>
            <el-tag v-else type="danger" size="mini">女</el-tag>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          width="132px"
          label="身份证号"
          prop="idcard"
        />

        <el-table-column
          align="center"
          class-name="status-col"
          label="负责工作"
          prop="job"
        />
        <el-table-column
          align="center"
          label="负责街区"
          prop="street"
        />

        <el-table-column
          align="center"
          label="电话号码"
          prop="tel"
        />
        <el-table-column
          width="170px"
          align="center"
          label="邮箱"
          prop="email"
        />
        <el-table-column
          align="center"
          label="家庭地址"
          prop="address"
        />
        <el-table-column width="70px" align="center" label="权限">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.role === 1" size="mini">普通</el-tag>
            <el-tag v-else type="warning" size="mini">super</el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作" width="238px">
          <template slot-scope="scope">
            <el-button
              class="rePassword"
              icon="el-icon-setting"
              size="mini"
              @click="resetRole(scope.row)"
            >重置密码</el-button>
            <el-button
              class="delete"
              icon="el-icon-delete"
              size="mini"
              @click="removeInformation(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :current-page="queryInfo.page"
        :page-size="10"
        layout="total,  prev, pager, next, jumper"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <el-dialog
      title="添加城管"
      :visible.sync="addVisible"
      width="50%"
      @close="closeDialog"
    >
      <span>
        <el-form
          ref="addRuleRef"
          :model="addForm"
          :rules="addRules"
          label-width="100px"
        >
          <el-form-item label="性别" prop="sex">
            <el-select v-model="addForm.sex" placeholder="请选择性别">
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </el-form-item>
          <el-form-item label="身份证号" prop="idcard">
            <el-input v-model="addForm.idcard" />
          </el-form-item>
          <el-form-item label="工作岗位" prop="job">
            <el-input v-model="addForm.job" />
          </el-form-item>
          <el-form-item label="负责街区" prop="street">
            <el-input v-model="addForm.street" />
          </el-form-item>
          <el-form-item label="电话号码" prop="tel">
            <el-input v-model="addForm.tel" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email" />
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input v-model="addForm.address" />
          </el-form-item>
          <el-form-item label="权限" prop="role">
            <el-select v-model="addForm.role" placeholder="请选择权限">
              <el-option label="普通用户" value="1" />
              <el-option label="超级用户" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="姓名" prop="realname">
            <el-input v-model="addForm.realname" />
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button class="rePassword" @click="addVisible = false">取 消</el-button>
        <el-button class="detail" @click="addNewManagement">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchList,
  addArticle,
  deleteArticle,
  resetArticle
} from '@/api/management'

export default {
  name: 'InlineEditTable',
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    // 验证邮箱的规则
    const checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }

      cb(new Error('请输入合法的邮箱'))
    }

    // 验证手机号的规则
    const checkMobile = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        // 合法的手机号码
        return cb()
      }
      cb(new Error('手机号码格式不正确'))
    }
    const chinaIdentityValid = (rule, value, callback) => {
      if (!value) {
        return callback()
      }
      const city = {
        11: '北京',
        12: '天津',
        13: '河北',
        14: '山西',
        15: '内蒙古',
        21: '辽宁',
        22: '吉林',
        23: '黑龙江 ',
        31: '上海',
        32: '江苏',
        33: '浙江',
        34: '安徽',
        35: '福建',
        36: '江西',
        37: '山东',
        41: '河南',
        42: '湖北 ',
        43: '湖南',
        44: '广东',
        45: '广西',
        46: '海南',
        50: '重庆',
        51: '四川',
        52: '贵州',
        53: '云南',
        54: '西藏 ',
        61: '陕西',
        62: '甘肃',
        63: '青海',
        64: '宁夏',
        65: '新疆',
        71: '台湾',
        81: '香港',
        82: '澳门',
        91: '国外'
      }
      if (
        !value ||
        !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(
          value
        )
      ) {
        callback(new Error('身份证号格式错误'))
      } else if (!city[value.substr(0, 2)]) {
        callback(new Error('身份证号格式错误'))
      } else {
        // 18位身份证需要验证最后一位校验位
        if (value.length === 18) {
          const code = value.split('')
          // ∑(ai×Wi)(mod 11)
          // 加权因子
          const factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
          // 校验位
          const parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2]
          let sum = 0
          let ai = 0
          let wi = 0
          for (let i = 0; i < 17; i++) {
            ai = code[i]
            wi = factor[i]
            sum += ai * wi
          }
          if (parity[sum % 11].toString() !== code[17]) {
            callback(new Error())
          }
        }
      }
      callback()
    }

    return {
      list: [],
      // 查询条件
      queryInfo: {
        page: 1,
        key: null,
        street: null
      },
      // 创建的对话框
      addVisible: false,
      // 角色权限
      roles: [1, 2],

      // 可视框数据
      addForm: {
        sex: '',
        idcard: '',
        job: '',
        street: '',
        tel: null,
        email: '',
        address: '',
        role: '',
        realname: ''
      },
      addRules: {
        sex: [{ required: true, message: '请输入性别', trigger: 'blur' }],
        idcard: [
          { required: true, message: '请输入身份证号码', trigger: 'blur' },
          {
            pattern: /(^\d{8}(0\d|10|11|12)([0-2]\d|30|31)\d{3}$)|(^\d{6}(18|19|20)\d{2}(0\d|10|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$)/,
            message: '请输入正确的证件号',
            trigger: 'blur'
          },
          { validator: chinaIdentityValid, trigger: 'blur' }
        ],
        job: [
          {
            required: true,
            message: '请输入工作岗位（类别用数字）',
            trigger: 'blur'
          }
        ],
        street: [
          { required: true, message: '请输入负责所在街区', trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        address: [
          { required: true, message: '请输入家庭住址', trigger: 'blur' }
        ],
        role: [{ required: true, message: '请选择权限', trigger: 'blur' }],
        realname: [{ required: true, message: '请输入姓名', trigger: 'blur' }]
      },
      roleId: ''
    }
  },
  created() {
    this.getInformation()
  },
  methods: {
    getTheseInfo() {
      this.handleCurrentChange(1)
    },
    getInformation() {
      this.listLoading = true
      fetchList(this.queryInfo).then((response) => {
        this.list = response.data
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },

    // 获取新的页数
    handleCurrentChange(newPage) {
      this.queryInfo.page = newPage
      this.getInformation()
    },
    // 新增加城管
    addNewManagement() {
      this.addForm.role = parseInt(this.addForm.role)
      this.addForm.tel = parseInt(this.addForm.tel)
      this.addForm.job = parseInt(this.addForm.job)
      this.addForm.street = parseInt(this.addForm.street)
      this.$refs['addRuleRef'].validate((valid) => {
        if (valid) {
          addArticle(this.addForm).then((response) => {
            this.$alert(
              '您的账号为：' +
                response.data.account +
                ' ' +
                '密码为：' +
                response.data.pwd,
              '标题名称',
              {
                confirmButtonText: '确定'
              }
            )
            this.list.unshift(this.addForm)
            this.addVisible = false
            this.$notify({
              title: 'Success',
              message: '创建城管成功',
              type: 'success',
              duration: 2000
            })
            this.getInformation()
          })
        }
      })
    },
    // 删除城管
    removeInformation(role) {
      this.$confirm('此操作将永久删除该城管, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.roleId = role.aid
          this.listLoading = true
          deleteArticle(this.roleId).then((response) => {
            this.getInformation()
            // Just to simulate the time of the request
            setTimeout(() => {
              this.listLoading = false
            }, 1.5 * 1000)
          })

          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 重置密码
    resetRole(role) {
      this.$confirm('重置该城管的密码, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.roleId = role.aid
          this.listLoading = true
          resetArticle(this.roleId).then((response) => {
            this.getInformation()
            // Just to simulate the time of the request
            setTimeout(() => {
              this.listLoading = false
            }, 1.5 * 1000)
          })

          this.$message({
            type: 'success',
            message: '重置成功,回归初始密码!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消重置'
          })
        })
    },

    // dialog关闭
    closeDialog() {
      this.$refs.addRuleRef.resetFields()
    }
  }
}
</script>

<style scoped>
.el-pagination{
  text-align: center;
}
.addUser {
  background-color: teal;
  color: #fff;
  border-radius: 10px;
  border: none;
}
.addUser:hover {
  background-color: rgb(2, 34, 122);
  color: #fff;
  border-radius: 10px;
  border: none;
}
.detail {
  background-color: lightseagreen;
  color: #fff;
  border-radius: 10px;
  border: none;
}
.detail:hover {
  background-color: rgb(34, 149, 194);
  color: #fff;
  border-radius: 10px;
  border: none;
}
.rePassword {
  background-color: coral;
  color: #fff;
  border-radius: 10px;
  border: none;
}
.rePassword:hover {
  background-color: rgb(245, 89, 42);
  color: #fff;
  border-radius: 10px;
  border: none;
}
.delete {
  background-color: tomato;
  color: #fff;
  border-radius: 10px;
  border: none;
}
.delete:hover {
  background-color: rgb(248, 46, 46);
  color: #fff;
  border-radius: 10px;
  border: none;
}
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
.el-pagination {
  margin-top: 10px;
}
.el-table {
  margin-top: 15px;
}
</style>
